<template>
  <div class="address-container">
    <button class="back-button" @click="goBack">
      <span class="back-icon">←</span>
      <span class="back-text">返回</span>
    </button>
    
    <div class="address-header">
      <h2>收货地址</h2>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        新增地址
      </el-button>
    </div>

    <div v-if="addressList.length === 0" class="empty-address">
      <el-empty description="暂无收货地址" />
    </div>

    <div v-else class="address-list">
      <div v-for="item in addressList" :key="item.id" class="address-item">
        <div class="address-info">
          <div class="address-header">
            <span class="recipient">{{ item.recipient }}</span>
            <span class="phone">{{ formatPhone(item.phone) }}</span>
            <el-tag v-if="item.isDefault === 1" type="success" size="small" effect="light">默认地址</el-tag>
          </div>
          <div class="address-detail">
            {{ item.province }} {{ item.city }} {{ item.district }} {{ item.detailedAddress }}
          </div>
        </div>
        <div class="address-actions">
          <el-button type="primary" text @click="handleEdit(item)">编辑</el-button>
          <el-button type="danger" text @click="handleDelete(item.id)">删除</el-button>
          <el-button v-if="item.isDefault === 0" type="success" text @click="handleSetDefault(item.id)">
            设为默认
          </el-button>
        </div>
      </div>
    </div>

    <!-- 新增/编辑地址对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
      destroy-on-close
    >
      <el-form :model="addressForm" :rules="rules" ref="addressFormRef" label-width="100px">
        <el-form-item label="收货人" prop="recipient">
          <el-input v-model="addressForm.recipient" placeholder="请输入收货人姓名" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="addressForm.gender">
            <el-radio :label="1">先生</el-radio>
            <el-radio :label="2">女士</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="addressForm.phone" placeholder="请输入手机号码" maxlength="11" />
        </el-form-item>
        <el-form-item label="所在地区" prop="region">
          <div class="region-select">
            <el-select v-model="addressForm.provinceId" @change="choseProvince" placeholder="请选择省份">
              <el-option
                v-for="(item, index) in province"
                :key="index"
                :label="item.value"
                :value="item.id"
              ></el-option>
            </el-select>

            <el-select v-model="addressForm.cityId" @change="choseCity" placeholder="请选择城市">
              <el-option 
                v-for="(item, index) in city" 
                :key="index" 
                :label="item.value" 
                :value="item.id"
              ></el-option>
            </el-select>

            <el-select v-model="addressForm.districtId" @change="choseBlock" placeholder="请选择区县">
              <el-option
                v-for="(item, index) in block"
                :key="index"
                :label="item.value"
                :value="item.id"
              ></el-option>
            </el-select>
          </div>
          <div v-if="addressForm.province || addressForm.city || addressForm.district" class="selected-region">
            <span>已选择：</span>
            <span v-if="addressForm.province">{{ addressForm.province }}</span>
            <span v-if="addressForm.city">{{ addressForm.city }}</span>
            <span v-if="addressForm.district">{{ addressForm.district }}</span>
          </div>
        </el-form-item>
        <el-form-item label="详细地址" prop="detailedAddress">
          <el-input
            v-model="addressForm.detailedAddress"
            type="textarea"
            :rows="2"
            placeholder="请输入详细地址信息，如道路、门牌号、小区、楼栋号、单元等"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getAddressList, addAddress, updateAddress, deleteAddress, setDefaultAddress } from '@/axios/address'
import ChineseDistricts from '@/axios/area.js'
import { Plus } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'

export default {
  name: 'Address',
  components: {
    Plus
  },
  setup() {
    const router = useRouter()
    const addressList = ref([])
    const dialogVisible = ref(false)
    const dialogTitle = ref('')
    const addressFormRef = ref()

    // 省市区数据
    const province = ref([])
    const city = ref([])
    const block = ref([])
    const shi1 = ref([])
    const qu1 = ref([])

    const addressForm = ref({
      id: undefined,
      recipient: '',
      gender: 1,
      phone: '',
      province: '',
      provinceId: '',
      city: '',
      cityId: '',
      district: '',
      districtId: '',
      detailedAddress: ''
    })

    const rules = {
      recipient: [{ required: true, message: '请输入收货人姓名', trigger: 'blur' }],
      phone: [{ required: true, message: '请输入手机号码', trigger: 'blur' }],
      provinceId: [{ required: true, message: '请选择省份', trigger: 'change' }],
      cityId: [{ required: true, message: '请选择城市', trigger: 'change' }],
      districtId: [{ required: true, message: '请选择区县', trigger: 'change' }],
      detailedAddress: [{ required: true, message: '请输入详细地址', trigger: 'blur' }]
    }

    // 加载省市区数据
    const getCityData = () => {
      ChineseDistricts.forEach((item) => {
        province.value.push({
          id: item.code,
          value: item.name,
          children: item.cityList
        })
      })
      console.log('已加载省份数据:', province.value)
    }

    // 选择省份
    const choseProvince = (e) => {
      console.log('选择省份:', e)
      city.value = []
      block.value = []
      addressForm.value.city = ''
      addressForm.value.cityId = ''
      addressForm.value.district = ''
      addressForm.value.districtId = ''
      
      const selectedProvince = province.value.find(p => p.id === e)
      if (selectedProvince) {
        addressForm.value.provinceId = selectedProvince.id
        addressForm.value.province = selectedProvince.value
        shi1.value = selectedProvince.children
        
        shi1.value.forEach((citem) => {
          city.value.push({
            id: citem.code,
            value: citem.name,
            children: citem.areaList
          })
        })
        console.log('省份选择后的表单:', addressForm.value)
        console.log('可选城市列表:', city.value)
      }
    }

    // 选择城市
    const choseCity = (e) => {
      console.log('选择城市:', e)
      block.value = []
      addressForm.value.district = ''
      addressForm.value.districtId = ''

      const selectedCity = city.value.find(c => c.id === e)
      if (selectedCity) {
        addressForm.value.cityId = selectedCity.id
        addressForm.value.city = selectedCity.value
        qu1.value = selectedCity.children
        
        qu1.value.forEach((bitem) => {
          block.value.push({
            id: bitem.code,
            value: bitem.name
          })
        })
        console.log('城市选择后的表单:', addressForm.value)
        console.log('可选区县列表:', block.value)
      }
    }

    // 选择区县
    const choseBlock = (e) => {
      console.log('选择区县:', e)
      const selectedDistrict = block.value.find(b => b.id === e)
      if (selectedDistrict) {
        addressForm.value.districtId = selectedDistrict.id
        addressForm.value.district = selectedDistrict.value
        console.log('区县选择后的表单:', addressForm.value)
      }
    }

    // 获取地址列表
    const fetchAddressList = async () => {
      try {
        const res = await getAddressList()
        console.log('获取到的地址列表:', res)
        if (Array.isArray(res)) {
          addressList.value = res
        } else if (res.code === 1) {
          addressList.value = res.data
        } else {
          ElMessage.error(res.msg || '获取地址列表失败')
        }
      } catch (error) {
        console.error('获取地址列表失败:', error)
        ElMessage.error('获取地址列表失败')
      }
    }

    // 新增地址
    const handleAdd = () => {
      dialogTitle.value = '新增地址'
      addressForm.value = {
        id: undefined,
        recipient: '',
        gender: 1,
        phone: '',
        province: '',
        provinceId: '',
        city: '',
        cityId: '',
        district: '',
        districtId: '',
        detailedAddress: ''
      }
      dialogVisible.value = true
    }

    // 编辑地址
    const handleEdit = (row) => {
      dialogTitle.value = '编辑地址'
      addressForm.value = { 
        ...row,
        provinceId: '',
        cityId: '',
        districtId: ''
      }
      
      // 根据名称找到对应的ID
      const selectedProvince = province.value.find(p => p.value === row.province)
      if (selectedProvince) {
        addressForm.value.provinceId = selectedProvince.id
        choseProvince(selectedProvince.id)
        
        const selectedCity = city.value.find(c => c.value === row.city)
        if (selectedCity) {
          addressForm.value.cityId = selectedCity.id
          choseCity(selectedCity.id)
          
          const selectedDistrict = block.value.find(b => b.value === row.district)
          if (selectedDistrict) {
            addressForm.value.districtId = selectedDistrict.id
          }
        }
      }
      
      dialogVisible.value = true
    }

    // 删除地址
    const handleDelete = (id) => {
      ElMessageBox.confirm('确认删除该地址吗？', '提示', {
        type: 'warning'
      }).then(async () => {
        try {
          await deleteAddress(id)
          ElMessage.success('删除成功')
          fetchAddressList()
        } catch (error) {
          console.error('删除地址失败:', error)
        }
      })
    }

    // 设置默认地址
    const handleSetDefault = async (id) => {
      try {
        const res = await setDefaultAddress(id)
        console.log('设置默认地址结果:', res)
        if (res.code === 1) {
          ElMessage.success('设置默认地址成功')
          // 更新本地地址列表中的默认状态
          addressList.value.forEach(item => {
            item.isDefault = item.id === id ? 1 : 0
          })
        } else {
          ElMessage.error(res.msg || '设置默认地址失败')
        }
      } catch (error) {
        console.error('设置默认地址失败:', error)
        ElMessage.error('设置默认地址失败，请稍后重试')
      }
    }

    // 提交表单
    const handleSubmit = async () => {
      if (!addressFormRef.value) return
      
      await addressFormRef.value.validate(async (valid) => {
        if (valid) {
          try {
            if (addressForm.value.id) {
              await updateAddress(addressForm.value)
              ElMessage.success('更新成功')
            } else {
              await addAddress(addressForm.value)
              ElMessage.success('添加成功')
            }
            dialogVisible.value = false
            fetchAddressList()
          } catch (error) {
            console.error('保存地址失败:', error)
          }
        }
      })
    }

    // 格式化手机号
    const formatPhone = (phone) => {
      return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
    }

    // 返回上一页
    const goBack = () => {
      router.back()
    }

    onMounted(() => {
      getCityData()
      fetchAddressList()
    })

    return {
      addressList,
      dialogVisible,
      dialogTitle,
      addressFormRef,
      addressForm,
      rules,
      province,
      city,
      block,
      handleAdd,
      handleEdit,
      handleDelete,
      handleSetDefault,
      handleSubmit,
      choseProvince,
      choseCity,
      choseBlock,
      formatPhone,
      goBack
    }
  }
}
</script>

<style scoped>
.address-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 30px;
  background-color: #f8f9fa;
  min-height: calc(100vh - 60px);
  position: relative;
}

.back-button {
  position: absolute;
  top: 10px;
  left: 30px;
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 20px;
  background: white;
  border: none;
  border-radius: 30px;
  font-size: 16px;
  color: #2c3e50;
  cursor: pointer;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  z-index: 10;
}

.back-button:hover {
  transform: translateX(-4px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
  background: #f8f9fa;
}

.back-icon {
  font-size: 20px;
  font-weight: 500;
}

.back-text {
  font-weight: 500;
}

.address-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  margin-top: 40px;
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.address-header h2 {
  font-size: 24px;
  color: #2c3e50;
  margin: 0;
  font-weight: 600;
}

.empty-address {
  padding: 60px 0;
  text-align: center;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.address-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.address-item {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding: 20px;
  border-radius: 8px;
  background-color: #fff;
  transition: all 0.3s;
  border: 1px solid #ebeef5;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.address-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.address-info {
  flex: 1;
}

.address-header {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.recipient {
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
}

.phone {
  color: #666;
  font-size: 14px;
}

.address-detail {
  color: #666;
  font-size: 14px;
  line-height: 1.6;
  margin: 15px 0;
  padding-bottom: 15px;
  border-bottom: 1px dashed #ebeef5;
}

.address-actions {
  display: flex;
  justify-content: flex-end;
  gap: 20px;
  margin-top: 15px;
}

.address-actions .el-button {
  padding: 8px 15px;
  font-size: 14px;
  border-radius: 4px;
  font-weight: 500;
  transition: all 0.25s;
}

.address-actions .el-button:hover {
  opacity: 0.8;
}

/* 对话框样式优化 */
.el-dialog {
  border-radius: 8px;
  overflow: hidden;
}

.el-dialog__header {
  margin: 0;
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
}

.el-dialog__body {
  padding: 30px 20px;
}

.el-dialog__footer {
  border-top: 1px solid #ebeef5;
  padding: 15px 20px;
}

.region-select {
  display: flex;
  gap: 10px;
}

.region-select .el-select {
  flex: 1;
}

/* 表单样式优化 */
.el-form-item {
  margin-bottom: 25px;
}

.el-input__inner {
  border-radius: 4px;
}

.el-button--primary {
  border-color: #409EFF;
  padding: 12px 25px;
  font-size: 14px;
  border-radius: 4px;
  transition: all 0.3s;
}

.el-button--primary:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
  transform: translateY(-1px);
}

.selected-region {
  margin-top: 8px;
  font-size: 14px;
  color: #409EFF;
}

.selected-region span {
  margin-right: 8px;
}

.selected-region span:first-child {
  color: #606266;
}
</style> 